﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using MySql.Data.MySqlClient;
using YmtAuth.Domain.Model.Safe;
using YmtAuth.Domain.Repository;
using YmtAuth.Common;

namespace YmtAuth.Repository.MySQL
{
    public class UserDeviceAuthRepository : MySQLRepository<UserDeviceAuthEntity>, IUserDeviceAuthRepository
    {
        public UserDeviceAuthRepository()
            : base(ConfigurationManager.AppSettings["UserDeviceAuth_MySQLConnString"], "UserDeviceAuth")
        {
        }

        public UserDeviceAuthEntity FindUserDevice(int userid, string deviceId, byte type = 0)
        {
            var sql =
                "select `UserId`,`DeviceId`,`AuthStatus`,`AuthTime`,`CreateTime`,`AppSource`,`Description`,`LastLoginTime`,`LastUpdateTime`,`Type` from UserDeviceAuth where `UserId`=@UserId AND `DeviceId`=@DeviceId limit 1";
            var par =
                this.Parameters.AddInt("@UserId", userid)
                    .AddString("@DeviceId", deviceId)
                    //.AddByte("@Type", type)
                    .Build();

            return Query(sql, par, commandType: CommandType.Text).SingleOrDefault();
        }

        public IEnumerable<UserDeviceAuthEntity> FindUserFirstAuthDeviceInfo(int userId, int authStatus)
        {
            var par =
                this.Parameters.AddInt("@UserId", userId).Build();
            var sql =
                "select `UserId`,`DeviceId`,`AuthStatus`,`AuthTime`,`CreateTime`,`AppSource`,`Description`,`LastLoginTime`,`LastUpdateTime`,`Type` from UserDeviceAuth where `UserId`=@UserId AND `AuthStatus` in(200,-200) limit 1";

            return Query(sql, par, commandType: CommandType.Text);
        }

        public bool Exists(int userid, string deviceid, byte type = 0)
        {
            var sql =
                "select 1 from UserDeviceAuth where `UserId`=@UserId AND `DeviceId`=@DeviceId limit 1";
            var par =
                this.Parameters.AddInt("@UserId", userid)
                    .AddString("@DeviceId", deviceid)
                    //.AddByte("@Type", type)
                    .Build();
            using (var conn = new MySqlConnection(this.connString))
            {
                return conn.Query<int>(sql, par, commandType: CommandType.Text, commandTimeout: ConfigUtility.LoginSafeSQLCommandTimeOut).SingleOrDefault() == 1;
            }
        }
        public UserDeviceAuthEntity FindLastDeviceAuthInfo(int userId, string devicerId)
        {
            var sql =
                 "select `UserId`,`DeviceId`,`AuthStatus`,`AuthTime`,`CreateTime`,`AppSource`,`Description`,`LastLoginTime`,`LastUpdateTime`,`Type` from UserDeviceAuth where `UserId`=@UserId AND `DeviceId`=@DeviceId order by AuthTime desc  limit 1";
            var par =
                this.Parameters.AddInt("@UserId", userId)
                    .AddString("@DeviceId", devicerId)
                //.AddByte("@Type", type)
                    .Build();

            return Query(sql, par, commandType: CommandType.Text).SingleOrDefault();

        }

        /// <summary>
        /// 更新用户所有 设备/ClientId 认证状态为“已认证”
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public int AuthUserDeviceSuccess(int userid)
        {
            var par = this.Parameters.AddInt("@UserId", userid).Build();
            string updateSql = "UPDATE userdeviceauth SET AuthStatus = 200, `AuthTime` = now(), `LastUpdateTime` = now(), `Description` = 'ManualAuthSuccess' where `UserId`=@UserId and AuthStatus != 200";

            using (var conn = new MySqlConnection(this.connString))
            {
                return conn.Execute(updateSql, par, commandTimeout: ConfigUtility.LoginSafeSQLCommandTimeOut);
            }
        }
    }
}
